#include <iostream>
#include <cstring>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>


void Usage(std::string proc)
{
    std::cerr << "Usage: " << "+ sever_ip " << "+ sever_port" << std::endl;
}
//./udpclint sever_ip sever_port
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string severip = argv[1];
    uint16_t severport = std::stoi(argv[2]);
    //创建一个套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "create socket error!\n" << std::endl;
        return 0;
    }
    struct sockaddr_in sever;
    memset(&sever, 0, sizeof(sever));
    sever.sin_family = AF_INET;
    sever.sin_port = htons(severport);
    sever.sin_addr.s_addr = inet_addr(severip.c_str());

    while(true)
    {
        //客户端输入数据
        std::cout << "please enter# ";
        std::string line;
        std::getline(std::cin,line);

        //写入
        sendto(sockfd, line.c_str(), line.size(), 0,
            (struct sockaddr*)&sever, sizeof(sever));

        //读取
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        int m = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&temp, &len);
        if(m > 0)
        {
            buffer[m] = 0;
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}